/**
 * 		-	ad-creatif	-
 * 		-	20/07/2012	-
 *
 * This class is the root, let user switching between differents games defined in gamelist.xml
 * It looks for the file preview.jpg to display a small preview of the game you wish to load.
 * 
 * 
**/


package screens {
	
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.*;
	
	import flash.display.StageDisplayState;
	import flash.events.Event;
	
	import org.flixel.FlxCamera;
	import org.flixel.FlxG;
	import org.flixel.FlxGroup;
	import org.flixel.FlxSprite;
	import org.flixel.FlxState;
	import org.flixel.FlxText;
	import org.flixel.plugin.photonstorm.FlxButtonPlus;
	
	import tools.ButtonFactory;
	import tools.MyFlxSprite;
	
	public class GameList extends FlxState {
		private var container:FlxGroup;
		private var template:Object;
		private var param:Array; //data for buttonFactory
		
		public function GameList() {
			
			//  fullscreen
			/*
				buttonFullScreen = new FlxButtonPlus(0, 0,toggle_fullscreen,null, "Fullscreen" );
				add(buttonFullScreen);
				
				textDimensions = new FlxText(0, 0, FlxG.width);
				textDimensions.alignment = "center";
				add(textDimensions);
				toggle_fullscreen(StageDisplayState.NORMAL);
				//FlxG.stage.addEventListener(Event.RESIZE, window_resized);
			*/
			
			FlxG.mouse.show();
		
			var loader:DataLoader = new XMLLoader("gameList.xml", {name: "gameList", skipFailed : true,onComplete: xmlLoaded});
			
			loader.load();
		}
		
		
		// all picturs are loaded
		private function fileLoadedCallBack(e:LoaderEvent):void{
				
			if(LoaderMax.getContent(template['btnImgUrl']))
				template['btnImg'] = LoaderMax.getContent(template['btnImgUrl'])['rawContent']['bitmapData'];
			
			if(LoaderMax.getContent(template['btnHoverImgUrl']))
				template['btnHoverImg'] = LoaderMax.getContent(template['btnHoverImgUrl'])['rawContent']['bitmapData'];
			
			if (LoaderMax.getContent(template['logoUrl'])) 
				template['logo'] = LoaderMax.getContent(template['logoUrl'])['rawContent']['bitmapData'];
			
			for each( var game:Object in Registry.gameList){
				if(LoaderMax.getContent(game.dirUrl + "preview.jpg")['rawContent'])
					game['preview'] = LoaderMax.getContent(game.dirUrl + "preview.jpg")['rawContent']['bitmapData'];
			}
			
			// display logo and button once loaded
			if(template.backgroundColor) FlxG.bgColor = template.backgroundColor;
			
			if (!template.logo) {
				var mainTitle_txt:FlxText = new FlxText(10, 20, FlxG.width, 'IEFM 3D GAME_MAKER');
				mainTitle_txt.color = FlxG.WHITE;
				mainTitle_txt.size = 60;
				mainTitle_txt.shadow = 0xffaaaaaa;
				add(mainTitle_txt);
			} else {
				var logo:FlxSprite = new MyFlxSprite().loadGraphicWithBitmap(template.logo);
				logo.height = 200;
				add(logo);
				
			}
			
			var buttons:ButtonFactory = new ButtonFactory(param, 420, 200, template);
			add(buttons);
			
		}
		
		
		// xml is loaded
		private function xmlLoaded(e:LoaderEvent):void{
			
			var xml:XML = e.target.content;
			Registry.gameList = {};
		
			//Load template datas
			
			var loader:LoaderMax = new LoaderMax({name: 'previews',onComplete: fileLoadedCallBack});
			
			template = {
				'backgroundColor' : checkString(xml.template.@backgroundColor),
				'fontFamily' : checkString(xml.template.@fontFamily),
				'fontSize' : checkNumber(xml.template.@fontSize),
				'fontColor' : checkString(xml.template.@fontColor),
				'btnImgUrl' : checkString(xml.template.@btnImgUrl),
				'btnHoverImgUrl' : checkString(xml.template.@btnHoverImgUrl),
				'btnSize' : checkNumber(xml.template.@btnSize),
				'logoUrl' : checkString(xml.template.@logoUrl)
			};
			
			if (template['btnImgUrl']) loader.append(new ImageLoader(template['btnImgUrl'], {'name' : template['btnImgUrl']}));
			if (template['btnHoverImgUrl']) loader.append(new ImageLoader(template['btnHoverImgUrl'], {'name' : template['btnHoverImgUrl']}));
			if (template['logoUrl']) loader.append(new ImageLoader(template['logoUrl'], {'name': template['logoUrl']}));
			
			param = [];
			
			for (var i:uint=0 ; i < xml.gameList.children().length(); i++) {
				
				var game:XML = xml.gameList.children()[i];
				
				loader.append(new ImageLoader(game.@dirUrl + "preview.jpg", {'name': game.@dirUrl + "preview.jpg"}))
				
				//store each game params in the Registry.gameList
					
				Registry.gameList[game.@name] = {
					'name': game.@name, 
					'link' : game.@link, 
					'description' : game.@description, 
					'dirUrl': game.@dirUrl
				};
				
				// add butons infos
				
				param.push({
					'label': String(game.@name), 
					'callBack' : onClick, 
					'hoverCallBack' : displayGameInfos
				});
			
			}
			
			loader.load();
			
			
			/********************************** CHECKING FUNCTIONS **********************************/
			
			// returns null if the attribute doesn't exist and eventually split arrays
			function checkNumber(number:*, returnArray:Boolean = false):*{
				if(number == xml.@azerty) return null;
				
				var tempArray:Array =  String(number).split(',');
				if (tempArray.length == 1 && !returnArray) return parseInt(tempArray[0]);
				
				else {
					for(var id:String in tempArray){
						if	(tempArray[id]== xml.@azerty)  number[id] = null;
						else  tempArray[id] = parseInt(tempArray[id]);
					}
				}
				return tempArray;
			}
			
			
			//returns null if the attribute doesn't exist and eventually split arrays
			function checkString(string:*, returnArray:Boolean = false):*{
				
				if(string == xml.@azerty) 
					return null;
				
				var tempArray:Array =  String(string).split(',');
				
				if (tempArray.length == 1 && !returnArray) 
					return tempArray[0];
				
				else 
					return tempArray;
			}
		}
		
		
		
		// Button click : launch game
		private function onClick(gameName:String):void{
			var game:PlayState = new PlayState();
			Registry.erase();
			Registry.gameName = gameName;
			FlxG.switchState(game);
		}
		
		// Button RollOver : displays Games Informations
		private function displayGameInfos(gameName:String):void{
			var infos:Object = Registry.gameList[gameName];
			if(container)  remove(container);
			container = new FlxGroup();
			
			var shape:FlxSprite = new FlxSprite(40,200);
			shape.makeGraphic(320,430,0x55555555);
			container.add(shape);
			
			var title:FlxText = new FlxText(50,210,300, infos['name']);
			title.size = 19;
			//if(template.fontFamily) title.font = String(template.fontFamily);
			container.add(title);
			
			if(infos['link']){
				var link:FlxText = new FlxText(50,250,300, 'lien : ' + infos['link']);
				//if(template.fontFamily) link.font = template.fontFamily;
				container.add(link);
			}
			if(infos['description']){
				var description:FlxText = new FlxText(50,270,300, 'description : ' + infos['description']);
				//if(template.fontFamily) description.font = template.fontFamily;
				container.add(description);
			}
			if(infos['preview']){
				var popup:MyFlxSprite = new MyFlxSprite(50, 390);
				popup.loadGraphicWithBitmap(Registry.gameList[gameName].preview,false,false,300);
				container.add(popup);
			}
				
			add(container);
		}
		
		//private static function progressHandler(event:LoaderEvent):void { trace("progress: ",  Math.floor(event.target.progress * 100) + " %"); }
		//private function errorHandler(event:LoaderEvent):void { trace("error occured with " + event.target + ": " + event.text); }
		
		
		/************************************************************************
		 * 							resize functions							*
		 ************************************************************************/
		
		private var buttonFullScreen:FlxButtonPlus;
		private var textDimensions:FlxText;
		private var ForceDisplayState:FlxState;
		
		private function toggle_fullscreen(ForceDisplayState:String=null):void {
			
			if (ForceDisplayState) {
				FlxG.stage.displayState = ForceDisplayState;
			} else {
				if (FlxG.stage.displayState == StageDisplayState.NORMAL) {
					FlxG.stage.displayState = StageDisplayState.FULL_SCREEN;
				} else {
					FlxG.stage.displayState = StageDisplayState.NORMAL;
				}
			}
			
			window_resized();
		}
		
		//fullscreen
		private function window_resized(e:Event=null):void {
			FlxG.width = FlxG.stage.stageWidth / FlxCamera.defaultZoom;
			FlxG.height = FlxG.stage.stageHeight / FlxCamera.defaultZoom;
			
			FlxG.resetCameras(new FlxCamera(0, 0, FlxG.width, FlxG.height));
			
			buttonFullScreen.x = FlxG.width / 2 - buttonFullScreen.width / 2;
			buttonFullScreen.y = FlxG.height / 2 - buttonFullScreen.height / 2;
			textDimensions.width = FlxG.width;
			textDimensions.text = "Current resolution: " + FlxG.width + "*" + FlxG.height;
		
		}
		
		
		
		
		
		
	}
}
